package main;

import dataediter.TableWR;
import frame.IndexFrame;
import frame.LoginFrame;
import other.Tool;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 核心管理类
 *
 * @author fdh
 */
public class Manager {
    private static Manager instance;
    public ArrayList<String> allTableFile = new ArrayList<>();
    public ArrayList<String> allDataFile = new ArrayList<>();
    public HashMap<String, String[][]> allTableData = new HashMap<>();
    public HashMap<String, String[]> allTableColName = new HashMap<>();
    public String currentTableFile = "-1";
    public String preTableFile = "-1";

    public enum AllPage {
        loginPage, indexPage
    }


    public Manager() {
        new Tool();
        //扫描表格文件
        TableWR.searchTableFilesFromPath(allTableFile);
        //解析表格文件
        getTablesFromDir();
        //设置显示页面
        setPage(AllPage.indexPage);

        System.out.println("程序跑起来啦,希望别bug，保佑,保佑(^~^)!!!!");
    }

    public static Manager getInstance() {
        return instance;
    }

    /**
     * 程序启动入口
     */
    public static void startApplication() {
        if (instance == null)
            instance = new Manager();
    }

    public void setCurrentTableFile(String tableFile) {
        preTableFile = currentTableFile;
        currentTableFile = tableFile;
    }

    /**
     * 启动指定页面
     *
     * @param currentPage 指定页面
     */
    public void setPage(AllPage currentPage) {
        switch (currentPage) {
            case loginPage:
                new LoginFrame();
                break;
            case indexPage:
                new IndexFrame();
                break;
        }
    }

    /**
     * 解析表格文件
     */
    public void getTablesFromDir() {
        TableWR tb = new TableWR();
        for (String file : allTableFile) {
            try {
                tb.setFile(file);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                System.out.println("表格文件读取失败:" + file);
                return;
            }
            ArrayList<String[]> data = new ArrayList<>();
            tb.readFromTableFile(data);
            String[] col = TableWR.getColFromArray(data);
            String[][] datas = TableWR.getDataFromArray(data);
            if (datas != null) {
                allTableData.put(file, datas);
            } else {
                allTableData.put(file, Tool.getInstance().setArrayEmpty(new String[Resource.Config.tableMaxRowCount][Resource.Config.tableDefaultColCount]));
            }
            if (col != null) {
                allTableColName.put(file, col);
            } else {
                allTableColName.put(file, Tool.getInstance().setArrayEmpty(new String[Resource.Config.tableDefaultColCount]));
            }
        }
        System.out.println("表格数据文件读取完毕");
    }
}
